package com.cxs.migrationdemo.slice;

import com.cxs.migrationdemo.ResourceTable;
import com.cxs.migrationdemo.util.DeviceUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;

public class MigrationAbilitySlice extends AbilitySlice implements IAbilityContinuation {
    TextField textField;
    String inputStr = "请输入";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_migration);

        textField = (TextField) findComponentById(ResourceTable.Id_text_input_migration);
        // 开始迁移后，目标设备上的onRestoreData方法将被调用(onStart之前)
        // 此时在onRestoreData方法中将可以获取到源设备传递过来的参数inputStr
        textField.setText(inputStr);  // 把inputStr的值赋给textField

        Button btnMigration = (Button)findComponentById(ResourceTable.Id_btn_migration);
        btnMigration.setClickedListener(c -> {
            // 获取设备Id
            String deviceId = DeviceUtils.getDeviceId();
            if (deviceId != null) {
                // 开始迁移
                continueAbility(deviceId);
            }

        });
    }


    // 开始迁移后源设备首先调用该方法
    @Override
    public boolean onStartContinuation() {
        return true;
    }

    // 开始迁移后，如果onStartContinuation()返回true，则源设备回调此方法进行数据存储
    @Override
    public boolean onSaveData(IntentParams intentParams) {
        intentParams.setParam("data", textField.getText());
        return true;
    }

    // 开始迁移后，在迁移的目标设备上调用（在onStart()之前调用）
    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        inputStr = intentParams.getParam("data").toString();
        return true;
    }

    @Override
    public void onCompleteContinuation(int i) {
        // 如果希望迁移完成之后关闭本地设备的Ability
        terminateAbility();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

}
